package utils

import (
	"crypto/md5"
	"encoding/hex"
	"io"
	"mime/multipart"
	"sort"
	"strings"
)

// 根据关联文件 获取文件MD5
func GetHeadFileMD5(file *multipart.FileHeader) (md5Str string, err error) {
	var targetFile multipart.File
	if targetFile, err = file.Open(); nil != err {
		return md5Str, err
	}
	defer targetFile.Close()

	md5Handle := md5.New()
	if _, err = io.Copy(md5Handle, targetFile); nil != err {
		return md5Str, err
	}

	md5str := hex.EncodeToString(md5Handle.Sum(nil))
	return md5str, err
}

// EncodeAliPaySignParams 验签参数处理
func EncodeAliPaySignParams(params map[string]string) string {
	var (
		buf     strings.Builder
		keyList []string
	)

	for k := range params {
		keyList = append(keyList, k)
	}
	sort.Strings(keyList)

	for _, k := range keyList {
		if v := params[k]; v != "" && k != "sing" {
			buf.WriteString(k)
			buf.WriteByte('=')
			buf.WriteString(v)
			buf.WriteByte('&')
		}
	}
	if buf.Len() <= 0 {
		return ""
	}
	return buf.String()[:buf.Len()-1]
}
